//
//  AListLookupController.m
//  MClient
//
//  Created by  wangfei on 10-4-6.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//
#import "EGORefreshTableHeaderView.h"
#import "AListLookupController.h"
#import "MClientAppDelegate.h"
#import "MServerDAO.h"
#import "QueryController.h"
#import "EditFormController.h"
#import "MCUIToolkit.h"
#import "CustomFormController.h"

@interface AListLookupController (Private)
- (Boolean)isMultiSelect;
- (void)initMultiItems:(NSString *)aValue label:(NSString *)aLabel;
- (void)initSingleItem:(NSString *)aValue label:(NSString *)aLabel;
- (void)refreshFinished;
@end


@implementation AListLookupController

@synthesize dataObjectName;
@synthesize queryFilter;
@synthesize page;
@synthesize listData;
@synthesize listLayout;
@synthesize fieldData;
@synthesize valueField;
@synthesize field;
@synthesize datas;
@synthesize fieldName;
@synthesize lookupBackFills;


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	[super viewDidLoad];
		
	self.title = [listLayout objectForKey:@"lbl"];
	self.tableview.backgroundColor = [UIColor clearColor];
	self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
	
	cellWidth = self.width;
	cellHeight = 0.0;
	imageWidth = 0.0;
	imageHeight = 0.0;
	imagesCache = [[NSMutableDictionary alloc] init];
	
	isJump2Page = ![[[listLayout objectForKey:@"csty"] objectForKey:@"scroll2page"] intValue];
	if (isJump2Page) {
		pageBar = [MCUIToolkit getPageBar:[MCUIToolkit hasQueryField:listLayout] delegate:self];
		[self.clientView addSubview:pageBar];
		pageBar.frame = CGRectMake(0, self.height-nToolBarHeight, self.width, nToolBarHeight);
		pageBar.autoresizingMask = nMCViewAutoresizingMask;
		self.tableview.frame = CGRectMake(0, 0, self.width, self.height-pageBar.frame.size.height);
		pageBar.hidden = YES;
	}/* else {
		if (refreshHeaderView == nil) {
			refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, self.tableview.bounds.size.height, self.width, 65.0f)];
			refreshHeaderView.backgroundColor = [UIColor clearColor];
			[self.tableview addSubview:refreshHeaderView];
			self.tableview.showsVerticalScrollIndicator = YES;
			[refreshHeaderView release];
		}
	}*/

	if ([self isMultiSelect]) {
		[self rightBarButton:@"确定" withStyle:UIBarButtonItemStyleDone selector:@selector(selectAction:)];
		[self initMultiItems:[self.fieldData objectForKey:@"value"] label:[self.fieldData objectForKey:@"lbl"]];
	}
	else {
		[self initSingleItem:[self.fieldData objectForKey:@"value"] label:[self.fieldData objectForKey:@"lbl"]];
	}
	// 根据配置显示/隐藏帮助按钮
	self.addHelpButton = YES;
	self.helpUrl = @"/iphone/help/chapter05-03-05.html";
	aListInfo = [[NSMutableDictionary alloc] init];
}


- (void)dealloc {
	[pageBar release];
	[dataObjectName release];
	[queryFilter release];
	[listData release];
	[listLayout release];
	[valueBufferArray release];
	[labelBufferArray release];
	[fieldData release];
	[field release];
	[valueField release];
	[datas release];
	[fieldName release];
	[lookupBackFills release];
	[aListInfo release];
	[imagesCache release];
	[refreshHeaderView release];
	[refreshHeaderView_Up release];
	[multiLookupBack release];
    [super dealloc];
}

#pragma mark ---UIToolbar事件---
-(void)goFirst:(id)inSender {
	if (page != 1) {
		page = 1;
		[self getDataFromServer];
	}
}

-(void)goPrevious:(id)inSender {
	if (page > 1) {
		page = page - 1;
		[self getDataFromServer];
	}
}

-(BOOL)goNext:(id)inSender {
	if (page < totalPage) {
		page = page + 1;
		[self getDataFromServer];
		return YES;
	} else {
		return NO;
	}
}

-(void)goLast:(id)inSender {
	if (page != totalPage) {
		page = totalPage;
		[self getDataFromServer];
	}
}

-(void)gotoPage:(id)inSender {
	UITextField *inputView = (UITextField *)[((UIBarButtonItem *)[pageBar.items objectAtIndex:4]).customView viewWithTag:1];
	int goPage = [inputView.text intValue];
	if (goPage >= 1 && goPage <= totalPage) {
		page = goPage;
		[self getDataFromServer];
	}
}

-(void)reload:(id)inSender {
	[self getDataFromServer];
}

-(void)search:(id)inSender {
	QueryController *queryController = [[QueryController alloc] initWithStyle:UITableViewStylePlain];
	queryController.listLayout = self.listLayout;
	queryController.queryFilter = self.queryFilter;
	[self.navigationController pushViewController:queryController animated:YES];
	[queryController release];
}

#pragma mark ---- 数据加载方法 ----
- (void)getDataFromServer {
	[(UITextField *)[((UIBarButtonItem *)[pageBar.items objectAtIndex:4]).customView viewWithTag:1] resignFirstResponder];
	[imagesCache removeAllObjects];
	[[MServerDAO sharedInstance] getListDataAsync:dataObjectName 
									   layoutName:[self.listLayout objectForKey:@"layout"] 
									  queryFilter:queryFilter 
											 page:page
										 delegate:self];
}

- (void)getDataFromServerSuccess: (NSMutableDictionary *)returnValue {
	self.tableview.backgroundColor = [MCUserDefaults instance].listViewCellRectColor_Even;
	if (isJump2Page || [MCUserDefaults instance].dragListLastAndMore) {
		self.listData = [returnValue objectForKey:@"rl"];
	} else {
		if (self.listData == nil) {
			self.listData = [NSMutableArray arrayWithArray:[returnValue objectForKey:@"rl"]];
		} else {
			[self.listData addObjectsFromArray:[returnValue objectForKey:@"rl"]];
		}
	}
	[self refreshFinished];
		
	totalPage = 1;
	if ([returnValue objectForKey:@"tp"]) {
		totalPage = [[returnValue objectForKey:@"tp"] intValue];
	}
	if (totalPage == 0) {
		totalPage = 1;
	}
	
	if (totalPage < 2 && pageBar) {
		[pageBar removeFromSuperview];
		[pageBar release];
		pageBar = nil;
		self.tableview.frame = CGRectMake(0, 0, self.width, self.height);
	} else {
		pageBar.hidden = NO;
	}


	if (pageBar && [pageBar.items count] > 5) {
		UITextField *inputView = (UITextField *)[((UIBarButtonItem *)[pageBar.items objectAtIndex:4]).customView viewWithTag:1];
		inputView.text = @"";
		inputView.placeholder = [NSString stringWithFormat:@"%d", page];
		UILabel *pageLabel = (UILabel *)(UITextField *)[((UIBarButtonItem *)[pageBar.items objectAtIndex:4]).customView viewWithTag:2];
		pageLabel.text = [NSString stringWithFormat:@"/%d", totalPage];		
	}
	NSMutableArray *listFields = [listLayout objectForKey:@"item"];
	if ([listData count] > 0) {
		NSMutableDictionary *record = [listData objectAtIndex:0];
		for (int i = 0; i < [listFields count]; i++) {
			NSMutableDictionary *appItem = [listFields objectAtIndex:i];
			if ([[appItem objectForKey:@"v"] boolValue]) {
				NSString *fieldType = [MCUIToolkit getFieldType:appItem];
				NSString *name = [MCUIToolkit getFieldName:appItem];
				NSMutableDictionary *fieldSData = [[record objectForKey:@"data"] objectForKey:name];
				if ([fieldType isEqualToString:@"S"]) {
					imageWidth = nImageWidthOfCell;
					imageHeight = nImageHeightOfCell;
					NSMutableDictionary *style = [fieldSData objectForKey:@"style"];
					if (nil != style) {
						if ([style objectForKey:@"width"]) {
							imageWidth = [[style objectForKey:@"width"] floatValue];
						}
						if ([style objectForKey:@"height"]) {
							imageHeight = [[style objectForKey:@"height"] floatValue];
						}
					}
					if (imageWidth > self.width) {
						imageHeight = self.width * imageHeight / imageWidth;
						imageWidth = self.width;
					}
					cellWidth = self.width - imageWidth;
				}
			}
		}
	}
	if ([self.view viewWithTag:-963]) {
		[[self.view viewWithTag:-963] removeFromSuperview];
	}
	if ([self.listData count] == 0) {
		self.tableview.hidden = YES;
		UILabel* label = [[UILabel alloc] initWithFrame:self.view.bounds];
		label.text = @"当前无数据！";
		label.backgroundColor = [UIColor clearColor];
		label.textAlignment = UITextAlignmentCenter;
		label.tag = -963;
		[self.view addSubview:label];
		[label release];
	}
	
	[self.tableview reloadData];
}

#pragma mark ---- UITableView处理方法 ----
//TableView的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return [self.listData count];
}

//每一行的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
	int row = [indexPath row];
	
	NSMutableArray *cellInfos = [MCUIToolkit getAListInfo:listLayout
												 listData:self.listData
												 rowIndex:row
												cellWidth:cellWidth];
	[aListInfo setObject:cellInfos forKey:[NSNumber numberWithInt:row]];
	if ([cellInfos count] <= 0) {
		return 0.0;
	}
	cellHeight = [[[cellInfos objectAtIndex:([cellInfos count] - 1)] objectForKey:@"cellHeight"] floatValue];
	if (cellHeight < imageHeight) {
		cellHeight = imageHeight + 12.0;
		return cellHeight;
	}
	if (cellHeight == 0.0) {
		return cellHeight;
	}
	if (cellHeight < 28.0) {
		return 44.0;
	}
	return cellHeight + 12.0;
}

//初始化TableVie根据参数和数据绘制每一行以及填充数据
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	int row = [indexPath row];
	UITableViewCell *cell = [MCUIToolkit getAListCell:[aListInfo objectForKey:[NSNumber numberWithInt:row]]
										  imagesCache:imagesCache	
											 rowIndex:row
										isMultiSelect:YES
											cellWidth:cellWidth
										   cellHeight:cellHeight
										   imageWidth:imageWidth
										  imageHeight:imageHeight];
	NSMutableDictionary *record = [self.listData objectAtIndex:row];
	for (int i = 0; i < [valueBufferArray count]; i++) {
		NSString *key = [valueBufferArray objectAtIndex:i];
		if ([[record objectForKey:@"key"] isEqualToString:key]) {
			cell.accessoryType = UITableViewCellAccessoryCheckmark;
			break;
		}
	}
	return cell;
}

//相应用户选中
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)newIndexPath {
	int row = [newIndexPath row];
	
	UITableViewCell *cell = [tableView cellForRowAtIndexPath:newIndexPath];
	NSMutableDictionary *record = [self.listData objectAtIndex:row];
	if ([self isMultiSelect]) {
		bool selectFlag = YES;
		for (int i = 0; i < [valueBufferArray count]; i++) {
			NSString *key = [valueBufferArray objectAtIndex:i];
			if ([[record objectForKey:@"key"] isEqualToString:key]) {
				[valueBufferArray removeObjectAtIndex:i];
				[labelBufferArray removeObjectAtIndex:i];
				selectFlag = NO;
				
				if(lookupBackFills != nil) {
					for(int i = 0; i<[lookupBackFills count]; i++){
						NSMutableDictionary *lookupBackFill = [lookupBackFills objectAtIndex:i];
						NSString *name = [lookupBackFill objectForKey:@"bf"];
						NSMutableDictionary *fieldsData = [[record objectForKey:@"data"] objectForKey:name];
						if (fieldsData != nil) {
							[MCFunction updateSelectedValue:[multiLookupBack objectAtIndex:i] 
												value:[fieldsData objectForKey:@"value"]
											 selected:selectFlag];
						}
					}
				}
				
				break;
			}
		}
		if (selectFlag) {
			cell.accessoryType = UITableViewCellAccessoryCheckmark;
			[valueBufferArray addObject:[record objectForKey:@"key"] == nil?@"":[record objectForKey:@"key"]];
			[labelBufferArray addObject:[record objectForKey:@"desc"] == nil?@"":[record objectForKey:@"desc"]];
			
			if(lookupBackFills != nil) {
				for(int i = 0; i<[lookupBackFills count]; i++){
					NSMutableDictionary *lookupBackFill = [lookupBackFills objectAtIndex:i];
					NSString *name = [lookupBackFill objectForKey:@"bf"];

					NSMutableDictionary *fieldsData = [[record objectForKey:@"data"] objectForKey:name];
					if (fieldsData != nil) {
						[MCFunction updateSelectedValue:(NSMutableArray *)[multiLookupBack objectAtIndex:i]  
											value:((NSString *)[fieldsData objectForKey:@"value"])
										 selected:selectFlag];
					}
				}
			}
		}else {
			cell.accessoryType = UITableViewCellAccessoryNone;
		}	
	}else {
		valueBufferArray = [[NSMutableArray alloc] init];
		labelBufferArray = [[NSMutableArray alloc] init];		
		[valueBufferArray addObject:[record objectForKey:@"key"] == nil?@"":[record objectForKey:@"key"]];
		[labelBufferArray addObject:[record objectForKey:@"desc"] == nil?@"":[record objectForKey:@"desc"]];

		NSString *valueString = [valueBufferArray objectAtIndex:0];
		NSString *labelString = [labelBufferArray objectAtIndex:0];
		
		[self.fieldData setObject:valueString forKey:@"value"];
		[self.fieldData setObject:labelString forKey:@"lbl"];
		self.valueField.text = labelString;
		
		NSMutableDictionary *fieldLabelData = [NSMutableDictionary dictionary];
		[fieldLabelData setObject:labelString forKey:@"value"];
		[datas setObject:fieldLabelData forKey:[@"__" stringByAppendingString:fieldName]];
		
		UIViewController *editFormController = [self.navigationController.viewControllers objectAtIndex:[self.navigationController.viewControllers count] - 2];
		if ([editFormController isKindOfClass:[EditFormController class]] || [editFormController isKindOfClass:[CustomFormController class]]) {
			if (lookupBackFills != nil) {
				for(int k = 0; k<[lookupBackFills count]; k++){
					NSMutableDictionary *lookupBackFill = [lookupBackFills objectAtIndex:k];
					NSString *name = [lookupBackFill objectForKey:@"bf"];
					NSMutableDictionary *recordData = [record objectForKey:@"data"];
					if (recordData == nil) {
						recordData = [NSMutableDictionary dictionary];
					}
					NSMutableDictionary *fieldDataLookupBack = [recordData objectForKey:name];
					if(fieldDataLookupBack == nil)
						fieldDataLookupBack = [NSMutableDictionary dictionary];
					if ([editFormController isKindOfClass:[EditFormController class]]) {
						[(EditFormController*)editFormController setLookupBackFillByFieldName: [lookupBackFill objectForKey:@"fld"] fieldDataLookupBack:fieldDataLookupBack];	
					} else if ([editFormController isKindOfClass:[CustomFormController class]]) {
						[(CustomFormController*)editFormController setLookupBackFillByFieldName: [lookupBackFill objectForKey:@"fld"] fieldDataLookupBack:fieldDataLookupBack];
					}
				}
			}
			if ([editFormController isKindOfClass:[EditFormController class]])
				[(EditFormController*)editFormController doCalcAction:((MCTextField*)valueField.control)];
		}
		[self.navigationController popViewControllerAnimated:YES];
	}
	[tableView deselectRowAtIndexPath:newIndexPath animated:YES];
}


//导航栏上动作按钮的点击事件
- (void) selectAction: (id) sender {
	@try {
		NSString *labelString = @"";
		NSString *valueString = @"";
		for(int i = 0;i<[valueBufferArray count]; i++) {
			valueString = [valueString stringByAppendingFormat:@"%@,",[valueBufferArray objectAtIndex:i]];
			labelString = [labelString stringByAppendingFormat:@"%@,",[labelBufferArray objectAtIndex:i]];
		}
		if ([labelString length] > 0) {
			labelString = [labelString substringToIndex:[labelString length] - 1];
			valueString = [valueString substringToIndex:[valueString length] - 1];
		}
		[self.fieldData setObject:valueString forKey:@"value"];
		[self.fieldData setObject:labelString forKey:@"lbl"];
		self.valueField.text = labelString;
		
		NSMutableDictionary *fieldLabelData = [[NSMutableDictionary alloc]init];
		[fieldLabelData setObject:labelString forKey:@"value"];
		[datas setObject:fieldLabelData forKey:[@"__" stringByAppendingString:fieldName]];
		
		if([self isMultiSelect] && lookupBackFills != nil) {
			for(int i = 0; i<[lookupBackFills count]; i++){
				NSMutableDictionary *lookupBackFill = [lookupBackFills objectAtIndex:i];
				NSString *name = [lookupBackFill objectForKey:@"fld"];
				NSMutableDictionary *recordData = [datas objectForKey:name];
				if (recordData == nil) {
					recordData = [NSMutableDictionary dictionary];
					[datas setObject:recordData forKey:name];
				} 
				[recordData setObject:[MCFunction getSelectedValue:[multiLookupBack objectAtIndex:i]] forKey:@"value"];
			}
			UIViewController *editFormController = [self.navigationController.viewControllers objectAtIndex:[self.navigationController.viewControllers count] - 2];
			if ([editFormController isKindOfClass:[MCEditTableViewController class]]) {
				[((MCEditTableViewController*)editFormController).tableview reloadData];
			}
		}
		
		[self.navigationController popViewControllerAnimated:YES];
	}
	@catch (NSException * e) {
		[[MCErrorManagement instance] doError:@"99" 
								returnMessage:[NSString stringWithFormat:@"main: Caught %@: %@", [e name], [e reason]]];	
	}
}


////初始化选中
//- (NSMutableArray *)initSelectedValue:(NSString*)aValue {
//	NSMutableArray *valueArray = [[NSMutableArray alloc] init];
//	
//	if (aValue != nil || [aValue isEqualToString:@""]) {
//		NSMutableArray *values = [[NSMutableArray alloc] initWithArray:[aValue componentsSeparatedByString:@","]];
//		for(int i = 0; i < [values count];i++) {
//			if (i == 0 || i == [values count] - 1) {
//				if ([[values objectAtIndex:i] isEqualToString:@""]) {
//					continue;
//				}
//			}
//			[valueArray addObject:[values objectAtIndex:i]];
//		}
//	}
//	return valueArray;
//}
//
////选中和不选中时更新
//- (void)updateSelectedValue:(NSMutableArray *)valueArray
//					  value:(NSString*)aValue
//				   selected:(bool)isSelect {
//	if(isSelect) {
//		if (aValue == nil || [aValue isEqualToString:@""]) {
//			//[valueBufferArray addObject:@""];
//			return;
//		}
//		
//		for (int i = 0; i < [valueArray count]; i++) {
//			NSString *value = [valueArray objectAtIndex:i];
//			if([aValue isEqualToString:value]) {
//				return;
//			}
//		}
//		[valueBufferArray addObject:aValue == nil?@"":aValue];
//	} else {
//		if (aValue == nil || [aValue isEqualToString:@""]) {
//			return;
//		}
//		for (int i = 0; i < [valueArray count]; i++) {
//			NSString *value = [valueArray objectAtIndex:i];
//			if([aValue isEqualToString:value]){
//				[valueArray removeObjectAtIndex:i];
//				return;
//			}
//		}			  
//	}
//}
//
////获取选中结果
//- (NSString *)getSelectedValue:(NSMutableArray *)valueArray {
//	NSString *result = @"";
//	for(int i = 0;i<[valueBufferArray count]; i++) {
//		NSString *value = [valueBufferArray objectAtIndex:i];
//		if (value == nil || [value isEqualToString:@""]) {
//			continue;
//		}
//		result = [result stringByAppendingFormat:@"%@,",value];
//	}
//	if ([result length] > 0) {
//		result = [result substringToIndex:[result length] - 1];
//	}
//	return result;
//}



- (void)initMultiItems:(NSString *)aValue label:(NSString *)aLabel {
	if(lookupBackFills != nil) {
		multiLookupBack = [[NSMutableArray alloc] init];
		
		for(int i = 0; i<[lookupBackFills count]; i++){
			NSMutableDictionary *lookupBackFill = [lookupBackFills objectAtIndex:i];
			NSString *name = [lookupBackFill objectForKey:@"fld"];
			NSMutableDictionary *recordData = [datas objectForKey:name];
			if (recordData == nil) {
				NSMutableArray *valueArray = [[NSMutableArray alloc] init];
				[multiLookupBack addObject:valueArray];
				[valueArray release];
			} else {
				NSMutableArray *valueArray = [MCFunction initSelectedValue:[recordData objectForKey:@"value"]];
				[multiLookupBack addObject:valueArray];
				[valueArray release];
			}
		}
	}
	
	labelBufferArray = [MCFunction initSelectedValue:aLabel];
	valueBufferArray = [MCFunction initSelectedValue:aValue];
	
//	labelBufferArray = [[NSMutableArray alloc] init];
//	valueBufferArray = [[NSMutableArray alloc] init];
//	
//	if (aValue == nil || [aValue isEqualToString:@""]) {
//		return;
//	}
//	
//	NSMutableArray *values = [[NSMutableArray alloc] initWithArray:[aValue componentsSeparatedByString:@","]];
//	for(int i = 0; i < [values count];i++) {
//		if (i == 0 || i == [values count] - 1) {
//			if ([[values objectAtIndex:i] isEqualToString:@""]) {
//				continue;
//			}
//		}
//		[valueBufferArray addObject:[values objectAtIndex:i]];
//	}
//	if (aLabel != nil && ![aLabel isEqualToString:@""]) {
//		NSMutableArray *labels = [[NSMutableArray alloc] initWithArray:[aLabel componentsSeparatedByString:@","]];
//		for(int i = 0; i < [labels count]; i++) {
//			[labelBufferArray addObject:[labels objectAtIndex:i]];
//		}	
//	}
	
	int count = [valueBufferArray count] - [labelBufferArray count];
	if (count > 0) {
		for (int i = 0; i < count; i++) {
			NSString *value = [[valueBufferArray objectAtIndex:i] copy];
			[labelBufferArray addObject:value];
		}
	}else if (count < 0) {
		for (int i = -count-1; i >= 0; i--) {
			[labelBufferArray removeObjectAtIndex:i];
		}
	}
}

- (void)initSingleItem:(NSString *)aValue label:(NSString *)aLabel {
	valueBufferArray = [[NSMutableArray alloc] init];
	labelBufferArray = [[NSMutableArray alloc] init];
	if (aValue != nil && ![aValue isEqualToString:@""]) {
		[valueBufferArray addObject:aValue];
		[labelBufferArray addObject:aLabel == nil?@"":aLabel];
	}
}

- (Boolean)isMultiSelect {
	NSString *fieldType = [field objectForKey:@"type"];
	if ([fieldType isEqualToString:@"U"]) {
		return YES;
	}
	return NO;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	int nScrollHeight = scrollView.bounds.size.height;
	if (!_reloading && refreshHeaderView &&
		scrollView.contentOffset.y+nScrollHeight >= scrollView.contentSize.height+ 65.0f &&
		[self goNext:nil]) {
		_reloading = YES;
		[refreshHeaderView setState:EGOOPullRefreshLoading];
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:0.2];
		scrollView.contentInset = UIEdgeInsetsMake(0.0f, 0.0f, 60.0f, 0.0f);
		[UIView commitAnimations];
	}
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{	
	
	if (scrollView.isDragging) {
		int nScrollHeight = scrollView.bounds.size.height;
		if (refreshHeaderView.state == EGOOPullRefreshPulling && refreshHeaderView &&
			scrollView.contentOffset.y+nScrollHeight >= scrollView.contentSize.height && 
			scrollView.contentOffset.y+nScrollHeight < scrollView.contentSize.height+65 && !_reloading) {
			[refreshHeaderView setState:EGOOPullRefreshNormal];
		} else if (refreshHeaderView.state == EGOOPullRefreshNormal && refreshHeaderView &&
				   scrollView.contentOffset.y+nScrollHeight >= scrollView.contentSize.height+65 && !_reloading) {
			[refreshHeaderView setState:EGOOPullRefreshPulling];
		}
	}
}

- (void)refreshFinished{
	
	_reloading = NO;
	
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:.3];
	[self.tableview setContentInset:UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0f)];
	[UIView commitAnimations];
	
	[refreshHeaderView setState:EGOOPullRefreshNormal];
	[refreshHeaderView refreshPage:page];  //  should check if data reload was successful 
}

@end
